package com.jt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class CacheDemoController01 {

      @Autowired
      private RedisTemplate redisTemplate;

      @GetMapping("/demo1/hello")
      public  String doSayHello(){
          ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
          String helloValue = valueOperations.get("hello");
          if(helloValue!=null)return helloValue;
          //假如这里在通过一些对象访问MySql数据库(耗时操作)
          System.out.println("==Get Data From Mysql===");
          String data="hello redis";//假设这个值来自数据库
          valueOperations.set("hello",data);
          return data;
      }
      //基于id查询博客信息
      @GetMapping("/demo1/blog/{id}")
      public Map<String,Object> doSelectById(@PathVariable Integer id){
          HashOperations<Integer,String,Object> hashOperations = redisTemplate.opsForHash();
          Map<String, Object> entries = hashOperations.entries(id);
          System.out.println(entries);
          if(entries!=null&&entries.size()!=0)return entries;
          System.out.println("==Get Data From Mysql===");
          Map<String,Object> map=new HashMap<>();//假设这个数据来自数据库
          map.put("id",id);
          map.put("title","redis");
          map.put("content","hello redis");
          hashOperations.putAll(id,map);
          return map;
      }
}
